package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.bean.crm.cgdd;
import com.example.bean.crm.cgddmx;
import com.example.bean.crm.skb;
import com.example.bean.crm.skbmx;
import com.example.service.crmService.crmService;
import com.example.service.k3Service.k3Service;
import com.example.utils.k3Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Map;

/**
 * 收款单
 * Created by tony on 2017/12/15.
 */
@Component
@RestController
public class skbSqlControl {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //定义k3Service
    @Autowired
    private k3Service k3Service;
    //定义mesService
    @Autowired
    private crmService crmService;

    /**
     * 收款单，生成收款单
     */
    @RequestMapping("/insertSk")
    @Scheduled(cron = "0 0/5 * * * ?") //每5执行一次
    public void insertSkScheduled() {
        logger.info("收款更新。开始……");
        //取得要处理的收款单
        ArrayList<skb> skbList = crmService.selectSkb();
        //遍历销售订单
        for (skb skb : skbList) {
            try {
                //是否已存入erp
                String erpFlg = skb.getERPskdaima();
                //更新
                if (erpFlg == null || erpFlg.isEmpty() || erpFlg.equals("")) {
                    //新增
                    k3Service.insertSk(skb);
                    Map<String, Object> sk = k3Service.selectSkInformation(skb.getSkbID());
                    //取得收款单明细
                    ArrayList<skbmx> skbmxList = crmService.selectSkbmx(skb.getSkbID());
                    String FBillNo = sk.get("FNUMBER").toString();
                    String FInterID = sk.get("FBILLID").toString();
                    if(skbmxList.size()==0){
                        skb.setClyf(3);
                        logger.info(skb.getSkbID()+"没有明细！");
                    }else{
                        //生成收款
                        for (skbmx skbmx : skbmxList) {
                            skbmx.setSkbID(FInterID);
                            k3Service.insertSkEntry(skbmx);
                        }
                        //已经成功添加
                        skb.setClyf(2);
                        logger.info(skb.getSkbID()+"生成收款单："+FBillNo+"生成成功！");
                    }

                } else {

                }
            } catch (Exception e) {
                //删除收款
                k3Service.deleteSk(skb.getSkbID());
                logger.error(skb.getSkbID()+e.getMessage());
                //异常
                skb.setClyf(3);

            }
            crmService.skbFlagRturn(skb);
        }

        logger.info("收款更新。结束……");
    }


}
